package com.hitalkie.teacher.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.hitalkie.teacher.R;
import com.hitalkie.teacher.adapter.LessonDetailStudentRvAdapter;
import com.hitalkie.teacher.adapter.TopicHintRvAdapter;
import com.hitalkie.teacher.app.TalkieApi;
import com.hitalkie.teacher.app.TalkieApplication;
import com.hitalkie.teacher.fragment.LoadingDialogFragment;
import com.hitalkie.teacher.model.BaseResponse;
import com.hitalkie.teacher.model.Lesson;
import com.hitalkie.teacher.model.Operation;
import com.hitalkie.teacher.model.User;
import com.hitalkie.teacher.tx.Constants;
import com.hitalkie.teacher.tx.CurLiveInfo;
import com.hitalkie.teacher.tx.MySelfInfo;
import com.hitalkie.teacher.util.OkHttpManager;
import com.hitalkie.teacher.util.Utils;
import com.hitalkie.teacher.widget.pageview.OnLastItemVisibleListener;
import com.hitalkie.teacher.widget.pageview.PageRecyclerView;
import com.squareup.picasso.Picasso;
import okhttp3.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;


/**
 * Date 25/09/2016
 *
 * @author charliema
 */
public class LessonDetailActivity extends BaseActivity {

    public final static String EXTRA_LESSON = "com.hitalkie.talkie.EXTRA_LESSON";

    private Lesson mLesson;

    private String mStudentListNext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        updateView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        updateData(mLesson);
    }

    private void initView() {
        setContentView(R.layout.view_lesson_detail);
        initTitleBar();
        initSrl();
        initTopicView();
        initHintView();
        initTeacherView();
        initStudentView();
        initApplyView();
        findViewById(R.id.llKejian).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent().setClass(getActivity(), LessonHintListActivity.class).putExtra(LessonHintListActivity.EXTRA_LESSON, mLesson));
            }
        });
    }

    private void initTitleBar() {
        findViewById(R.id.viewTitleBarLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

    }

    private void initSrl() {
        SwipeRefreshLayout srl = (SwipeRefreshLayout) findViewById(R.id.srl);
        assert srl != null;
        srl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateData(mLesson);
            }
        });
    }

    private void initTopicView() {
        RecyclerView rvTopicHint = (RecyclerView) findViewById(R.id.rvTopicHint);
        rvTopicHint.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvTopicHint.setAdapter(new TopicHintRvAdapter());
    }

    private void initHintView() {
        ImageView ivHint = (ImageView) findViewById(R.id.iv_hint);
        if (mLesson.topic != null && !TextUtils.isEmpty(mLesson.topic.cover)) {
            Picasso.with(ivHint.getContext()).load(mLesson.topic.cover)
                    .placeholder(R.drawable.ic_default_image)
                    .error(R.drawable.ic_default_image)
                    .fit().centerCrop()
                    .into(ivHint);
        }
    }

    private void initTeacherView() {
    }

    private void initStudentView() {
        PageRecyclerView rvStudent = (PageRecyclerView) findViewById(R.id.rvStudent);
        rvStudent.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvStudent.setAdapter(new LessonDetailStudentRvAdapter());
        rvStudent.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                getStudentList(mLesson, false);
            }
        });
        ((LessonDetailStudentRvAdapter) rvStudent.getAdapter()).setOnItemClickListener(new LessonDetailStudentRvAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(User data) {

            }

            @Override
            public void onEvaluate(User data) {
                evaluate(data);
            }

        });
    }

    private void initApplyView() {

    }

    private void initData() {
        mLesson = (Lesson) getIntent().getSerializableExtra(EXTRA_LESSON);
    }


    private void updateData(Lesson lesson) {
        getLessonDetail(lesson);
        getStudentList(lesson, true);
    }

    private void getLessonDetail(Lesson lesson) {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        Request.Builder reqBuilder = new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_LESSON + lesson.id);
        OkHttpManager.client.newCall(reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                                // loading dialog
                                loadingDialogFragment.dismiss();
                                ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                                }
                            });
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "lesson detail resp:" + jsonStr);

                        try {
                            final LessonDetailResp resp = new Gson().fromJson(jsonStr, LessonDetailResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        if (resp.lesson != null) {
                                            mLesson = resp.lesson;
                                            updateView();
                                        }
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    ((SwipeRefreshLayout) findViewById(R.id.srl)).setRefreshing(false);
                                }
                            });
                        }
                    }
                });
    }

    private static class LessonDetailResp extends BaseResponse {
        Lesson lesson;
    }

    private void getStudentList(Lesson lesson, final boolean isRefresh) {
        String url;
        if (isRefresh) {
            url = TalkieApi.getHost() + TalkieApi.PATH_LESSON + lesson.id + "/students/";
        } else {
            url = TalkieApi.getHost() + mStudentListNext;
        }
        Request.Builder reqBuilder = new Request.Builder().url(url);
        OkHttpManager.client.newCall(
                reqBuilder.build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();

                        try {
                            final StudentListResp resp = new Gson().fromJson(jsonStr, StudentListResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        PageRecyclerView rvStudent = (PageRecyclerView) findViewById(R.id.rvStudent);
                                        if (isRefresh) {
                                            // 刷新页面
                                            if (resp.students == null || resp.students.size() == 0) {
                                                findViewById(R.id.tvStudentEmpty).setVisibility(View.VISIBLE);
                                            } else {
                                                findViewById(R.id.tvStudentEmpty).setVisibility(View.GONE);
                                                ((LessonDetailStudentRvAdapter) rvStudent.getAdapter()).setData(resp.students);
                                            }
                                        } else {
                                            // 加载更多
                                            ((LessonDetailStudentRvAdapter) rvStudent.getAdapter()).addData(resp.students);
                                        }
                                        if (TextUtils.isEmpty(resp.next)) {
                                            // 到了最后一页
                                            rvStudent.loadingStatus = PageRecyclerView.State.END;
                                        } else {
                                            rvStudent.loadingStatus = PageRecyclerView.State.IDLE;
                                        }
                                        mStudentListNext = resp.next;
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                }
                            });
                        }
                    }
                });
    }

    private static class StudentListResp extends BaseResponse {
        List<User> students;
        String next;
    }

    private void updateView() {
        if (mLesson == null) {
            return;
        }
//        updateTopicView();
        updateTopicWebView();
        updateTimeView();
        updateTeacherView();
        updateApplyView();
    }

    private void updateTopicView() {
        if (mLesson.topic == null) {
            return;
        }
        if (!TextUtils.isEmpty(mLesson.topic.getTitle())) {
            ((TextView) findViewById(R.id.tvTopicTitle)).setText(mLesson.topic.getTitle());
        }
        RecyclerView rvTopicHint = (RecyclerView) findViewById(R.id.rvTopicHint);
        ((TopicHintRvAdapter) rvTopicHint.getAdapter()).setData(mLesson.topic.topic_hints);
    }

    private void updateTopicWebView() {
        if (mLesson.topic == null) {
            return;
        }
        WebView wv = (WebView) findViewById(R.id.wv);
        wv.loadUrl(mLesson.topic.detail_en);
    }

    private void updateTimeView() {
        long startTimeL = Long.parseLong(mLesson.start_time);
        String startTime = Utils.getUpdateTime(startTimeL);

        long endTimeL = startTimeL + (mLesson.duration * 60 * 1000);
        SimpleDateFormat format = new SimpleDateFormat("HH:mm", TalkieApplication.getLocale());
        String endTime = format.format(endTimeL);
        ((TextView) findViewById(R.id.tvTime)).setText("" + startTime + " ~ " + endTime);
        // 提醒按钮
//        TextView tvSubscribe = (TextView) findViewById(R.id.tvSubscribe);
//        if (mLesson.status == 1) {
//            tvSubscribe.setVisibility(View.VISIBLE);
//            if (mLesson.is_subscribed) {
//                tvSubscribe.setText(getText(R.string.cancel_remind));
//                tvSubscribe.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        unsubscribe();
//                    }
//                });
//            } else {
//                tvSubscribe.setText(getText(R.string.remind_me));
//                tvSubscribe.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        subscribe();
//                    }
//                });
//            }
//
//        } else {
//            tvSubscribe.setVisibility(View.GONE);
//
//        }
    }


    private void updateTeacherView() {
        if (mLesson.teachers == null || mLesson.teachers.size() == 0 || mLesson.teachers.get(0) == null) {
            findViewById(R.id.rlTeacherContent).setVisibility(View.GONE);
            findViewById(R.id.tvTeacherEmpty).setVisibility(View.VISIBLE);
            return;
        }
        findViewById(R.id.rlTeacherContent).setVisibility(View.VISIBLE);
        findViewById(R.id.tvTeacherEmpty).setVisibility(View.GONE);

        User teacher = mLesson.teachers.get(0);
        ((TextView) findViewById(R.id.tvTeacherName)).setText(teacher.name);
        ((TextView) findViewById(R.id.tvTeacherBio)).setText(teacher.home_country);
        ImageView ivTeacher = (ImageView) findViewById(R.id.ivTeacherAvatar);
        Picasso.with(ivTeacher.getContext()).load(teacher.avatar)
                .placeholder(R.drawable.ic_default_image)
                .error(R.drawable.ic_default_image)
                .fit().into(ivTeacher);
    }

    private void updateStudentView() {


    }

    private void updateApplyView() {
        if (mLesson.operations == null || mLesson.operations.get(0) == null) {
            findViewById(R.id.viewOperation).setVisibility(View.GONE);
            return;
        }
        final Operation operation = mLesson.operations.get(0);
        View viewOperation = findViewById(R.id.viewOperation);
        if (!TextUtils.isEmpty(operation.title)) {
            viewOperation.setVisibility(View.VISIBLE);
            TextView tvOperation = (TextView) findViewById(R.id.tvOperation_0);
            tvOperation.setText(operation.title);
        } else {
            viewOperation.setVisibility(View.GONE);
        }
        TextView tvOperation_1 = (TextView) findViewById(R.id.tvOperation_1);
        if (!TextUtils.isEmpty(operation.sub_title)) {
            tvOperation_1.setVisibility(View.VISIBLE);
            tvOperation_1.setText(operation.sub_title);
        } else {
            tvOperation_1.setVisibility(View.GONE);
        }
        if (TextUtils.isEmpty(operation.type)) {
            findViewById(R.id.viewOperation).setEnabled(false);
        } else {
            if (TextUtils.equals(operation.type, "finished")) {
                findViewById(R.id.viewOperation).setEnabled(false);
            } else {
                findViewById(R.id.viewOperation).setEnabled(true);
                viewOperation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (operation.type) {
                            case "apply":
                                apply(operation.href);
                                break;
                            case "verify":
                                // 进入直播 （先验证接口）
                                verify(operation.href);
                                break;
                            case "cancel":
                                // 当前用户可能是老师也可能是学生
                                cancel(operation.href);
                                break;
//                            case "review":
//                                // 当前用户是vip，当前课程已经结束，跳转进入 本课程的老师 评价 页面
//                                review(operation.href);
//                                break;
                            case "evaluate":
                                // 当前用户是老师，当前课程已经结束，跳转进入 本课程的vip列表 页面 ，下一步 进行打分
                                evaluate();
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
        }
    }

    /**
     * 点击提醒我
     */
    private void subscribe() {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_LESSON + mLesson.id + "/apply?type=2")
                        //
                        .post(new FormBody.Builder().build())
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();

                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        updateData(mLesson);
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                        if (resp.status.error_code == 403 || resp.status.error_code == 401) {
                                            // 登录授权失败
                                            TalkieApplication.signOut();
                                            startActivity(new Intent(getActivity(), SignInActivity.class));
                                        }
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                }
                            });

                        }
                    }
                });
    }

    /**
     * 取消提醒我
     */
    private void unsubscribe() {
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + TalkieApi.PATH_LESSON + mLesson.id + "/cancel?type=2")
                        //
                        .post(new FormBody.Builder().build())
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();

                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    if (resp.status.error_code == 0) {
                                        updateData(mLesson);
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                }
                            });

                        }
                    }
                });
    }

    /**
     * 学生订购课程，老师领取课程
     */
    private void apply(String href) {
        if (TextUtils.isEmpty(href)) {
            Toast.makeText(getActivity(), "操作的href为空", Toast.LENGTH_LONG).show();
            return;
        }
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + href)
                        //

                        .post(new FormBody.Builder().build())
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        try {
                            final BaseResponse resp = new Gson().fromJson(jsonStr, BaseResponse.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    if (resp.status.error_code == 0) {
                                        updateData(mLesson);
                                    } else {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                        if (resp.status.error_code == 403 || resp.status.error_code == 401) {
                                            // 登录授权失败
                                            TalkieApplication.signOut();
                                            startActivity(new Intent(getActivity(), SignInActivity.class));
                                        }
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                        }
                    }
                });


    }

    /**
     * 验证。验证结束 之后 进入课程
     */
    private void verify(String href) {
        if (TextUtils.isEmpty(href)) {
            Toast.makeText(getActivity(), "操作的href为空", Toast.LENGTH_LONG).show();
            return;
        }
        // loading dialog
        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

        OkHttpManager.client.newCall(
                new Request.Builder().url(TalkieApi.getHost() + href)
                        //
                        .post(new FormBody.Builder().build())
                        .build())
                //
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (!response.isSuccessful()) {
                            return;
                        }
                        String jsonStr = response.body().string();
                        Log.e(TAG, "verify resp:" + jsonStr);

                        try {
                            final VerifyResp resp = new Gson().fromJson(jsonStr, VerifyResp.class);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    // loading dialog
                                    loadingDialogFragment.dismiss();
                                    if (resp.status.error_code != 0) {
                                        Toast.makeText(getActivity(), resp.status.error_message, Toast.LENGTH_LONG).show();
                                        return;
                                    }
                                    // 进入直播前的验证（老师／学生）
                                    if (TextUtils.equals(resp.verification.get("type"), "normal")) {
                                        // 普通用户 直接进
//                                        Toast.makeText(getActivity(), "普通用户，围观", Toast.LENGTH_LONG).show();
                                        liveRoom("normal");
                                    } else if (TextUtils.equals(resp.verification.get("type"), "vip")) {
                                        // vip 验证
                                        if (TextUtils.equals(resp.verification.get("check"), Utils.md5(resp.verification.get("type") + mLesson.id + TalkieApplication.getToken()))) {
//                                            Toast.makeText(getActivity(), "预约用户，进入直播", Toast.LENGTH_LONG).show();
                                            liveRoom("vip");
                                        } else {
//                                            Toast.makeText(getActivity(), "验证失败，围观", Toast.LENGTH_LONG).show();
                                            liveRoom("normal");
                                        }
                                    } else if (TextUtils.equals(resp.verification.get("type"), "teacher")) {
                                        // teacher 验证
                                        if (TextUtils.equals(resp.verification.get("check"), Utils.md5(resp.verification.get("type") + mLesson.id + TalkieApplication.getToken()))) {
//                                            Toast.makeText(getActivity(), "验证成功，进入直播", Toast.LENGTH_LONG).show();
                                            liveRoom("teacher");
                                        } else {
                                            Toast.makeText(getActivity(), getResources().getString(R.string.verification_error), Toast.LENGTH_LONG).show();
                                        }
                                    }

                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            response.body().close();
                            new Handler(getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {
                                    loadingDialogFragment.dismiss();
                                }
                            });
                        }
                    }
                });
    }


    private void cancel(final String href) {
        if (TextUtils.isEmpty(href)) {
            Toast.makeText(getActivity(), "操作的href为空", Toast.LENGTH_LONG).show();
            return;
        }
        new AlertDialog.Builder(getActivity())
                .setTitle(getText(R.string.if_verification_cancel))
                .setPositiveButton(getText(R.string.cancel_appointment), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // loading dialog
                        final LoadingDialogFragment loadingDialogFragment = new LoadingDialogFragment();
                        loadingDialogFragment.show(getSupportFragmentManager(), "loading");

                        OkHttpManager.client.newCall(
                                new Request.Builder().url(TalkieApi.getHost() + href)
                                        //
                                        .post(new FormBody.Builder().build())
                                        .build())
                                //
                                .enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                        e.printStackTrace();
                                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(getActivity(), getResources().getString(R.string.network_exception), Toast.LENGTH_LONG).show();
                                            }
                                        });
                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        if (!response.isSuccessful()) {
                                            return;
                                        }
                                        String jsonStr = response.body().string();
                                        Log.e(TAG, "verify resp:" + jsonStr);

                                        try {
                                            final VerifyResp resp = new Gson().fromJson(jsonStr, VerifyResp.class);
                                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    // loading dialog
                                                    loadingDialogFragment.dismiss();

                                                }
                                            });
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        } finally {
                                            response.body().close();
                                            new Handler(getMainLooper()).post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    loadingDialogFragment.dismiss();
                                                }
                                            });
                                        }
                                    }
                                });
                    }
                })
                .setNegativeButton(getResources().getString(R.string.close), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }


    private void evaluate() {
        Intent i = new Intent(getActivity(), StudentListOfLessonActivity.class);
//        i.putExtra(StudentListOfLessonActivity.EXTRA_HREF, href);
        i.putExtra(StudentListOfLessonActivity.EXTRA_LESSON, mLesson);
        startActivity(i);
    }

    private void evaluate(User vip){
        Intent i = new Intent();
        i.setClass(getActivity(), EvaluationActivity.class);
        i.putExtra(EvaluationActivity.EXTRA_LESSON, mLesson);
        i.putExtra(EvaluationActivity.EXTRA_TEACHER, mLesson.teachers.get(0));
        i.putExtra(EvaluationActivity.EXTRA_VIP, vip);
        startActivity(i);
    }

    private void liveRoom(String type) {
        Intent intent;
        switch (type) {
            case "normal":
                intent = new Intent(getActivity(), LiveActivity.class);
                intent.putExtra("type", type); // 业务
                intent.putExtra(LiveActivity.EXTRA_LESSON, mLesson); // 业务

                intent.putExtra(Constants.ID_STATUS, Constants.MEMBER);
                MySelfInfo.getInstance().setIdStatus(Constants.MEMBER);
                MySelfInfo.getInstance().setJoinRoomWay(false);

                CurLiveInfo.setHostID("" + mLesson.teachers.get(0).im_user_id);
                CurLiveInfo.setHostName(mLesson.teachers.get(0).name);
                CurLiveInfo.setHostAvator(mLesson.teachers.get(0).avatar);
                CurLiveInfo.setRoomNum(mLesson.av_room_id);
                CurLiveInfo.setMembers(mLesson.audience_count_now + 1); // 添加自己
//                                        CurLiveInfo.setAdmires(item.getAdmireCount());
//                                        CurLiveInfo.setAddress(item.getLbs().getAddress());
                startActivity(intent);
                break;
            case "vip":
                intent = new Intent(getActivity(), LiveActivity.class);
                intent.putExtra("type", type); // 业务
                intent.putExtra(LiveActivity.EXTRA_LESSON, mLesson); // 业务

                intent.putExtra(Constants.ID_STATUS, Constants.VIDEO_MEMBER);
                MySelfInfo.getInstance().setIdStatus(Constants.VIDEO_MEMBER);
                MySelfInfo.getInstance().setJoinRoomWay(false);

                CurLiveInfo.setHostID("" + mLesson.teachers.get(0).im_user_id);
                CurLiveInfo.setHostName(mLesson.teachers.get(0).name);
                CurLiveInfo.setHostAvator(mLesson.teachers.get(0).avatar);
                CurLiveInfo.setRoomNum(mLesson.av_room_id);
                CurLiveInfo.setMembers(mLesson.audience_count_now + 1); // 添加自己
//                                        CurLiveInfo.setAdmires(item.getAdmireCount());
//                                        CurLiveInfo.setAddress(item.getLbs().getAddress());
                startActivity(intent);

                break;
            case "teacher":
                intent = new Intent(getActivity(), LiveActivity.class);
                intent.putExtra("type", type); // 业务
                intent.putExtra(LiveActivity.EXTRA_LESSON, mLesson); // 业务


                intent.putExtra(Constants.ID_STATUS, Constants.HOST);
                MySelfInfo.getInstance().setIdStatus(Constants.HOST);
                // 如果第一次进入就需要创建聊天室房间
                MySelfInfo.getInstance().setJoinRoomWay(true);

                MySelfInfo.getInstance().setMyRoomNum(mLesson.av_room_id);
                MySelfInfo.getInstance().writeToCache(getApplicationContext());

                CurLiveInfo.setHostID("" + mLesson.teachers.get(0).im_user_id);
                CurLiveInfo.setHostName(mLesson.teachers.get(0).name);
                CurLiveInfo.setHostAvator(mLesson.teachers.get(0).avatar);
                CurLiveInfo.setRoomNum(mLesson.av_room_id);
                CurLiveInfo.setMembers(mLesson.audience_count_now + 1); // 添加自己
//                                        CurLiveInfo.setAdmires(item.getAdmireCount());
//                                        CurLiveInfo.setAddress(item.getLbs().getAddress());
                startActivity(intent);
                break;
            default:
                break;

        }


    }

    private static class VerifyResp extends BaseResponse {
        String room_url;
        Map<String, String> verification;
//            "verification":{
//                  "check":"35d405545036e938d492412d2d93b04d",
//                  "type":"normal"  //teacher/vip/normal
//    }
    }


}
